using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using SaleOffVn.DataAccess;
using SaleOffVn.BusinessEntities;
using System.Data;

namespace SaleOffVn.BusinessLogic
{
    /// <summary>
    /// Picture manager
    /// </summary>
    public class PictureManager
    {
        public static DataTable GetAllPictures()
        {
            DataTable picCollection = null;
            picCollection = DBPicture.GetAllPictures();
            return picCollection;
        }

        public static int GetMaximumPictureID()
        {
            return DBPicture.GetMaximumPictureID();
        }
        
        public static int Add(string PictureThumbnail)
        {
            return DBPicture.Add(PictureThumbnail);
        }

        public static Picture GetPictureById(int imageId)
        {
            return DBPicture.GetPictureById(imageId);
        }        

        public static string GetPictureUrl(int imageId, int targetSize)
        {
            string url = string.Empty;
            string path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\thumbs";
            var picture = GetPictureById(imageId);
            if (picture != null)
            {
                string localFilename = string.Empty;
                string strTmp = picture.PictureThumbnail.Substring(0, picture.PictureThumbnail.Length - 4);
                localFilename = string.Format("{0}_{1}.{2}", strTmp.ToString(), targetSize, "gif");
                if (!File.Exists(Path.Combine(path, localFilename)))
                {
                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    string strPicFile = HttpContext.Current.Server.MapPath("~/Images/thumbs/") + picture.PictureThumbnail;
                    var b = new Bitmap(strPicFile);

                    var newSize = CalculateDimensions(b.Size, targetSize);

                    if (newSize.Width < 1)
                        newSize.Width = 1;
                    if (newSize.Height < 1)
                        newSize.Height = 1;

                    var newBitMap = new Bitmap(newSize.Width, newSize.Height);
                    var g = Graphics.FromImage(newBitMap);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    g.DrawImage(b, 0, 0, newSize.Width, newSize.Height);                    
                    newBitMap.Save(Path.Combine(path, localFilename));
                    newBitMap.Dispose();
                    b.Dispose();
                    
                }
                url = "images/thumbs/" + localFilename;
            }            
            return url;
        }

        public static Size CalculateDimensions(Size originalSize, int targetSize)
        {
            var newSize = new Size();
            if (originalSize.Height > originalSize.Width) // portrait 
            {
                newSize.Width = (int)(originalSize.Width * (float)(targetSize / (float)originalSize.Height));
                newSize.Height = targetSize;
            }
            else // landscape or square
            {
                newSize.Height = (int)(originalSize.Height * (float)(targetSize / (float)originalSize.Width));
                newSize.Width = targetSize;
            }
            return newSize;
        }

        public static List<String> GetPictureUrls(string strLocalThumbImagePath , Picture picture)
        {
            string filter = String.Empty;
            string strTmp = picture.PictureThumbnail.Substring(0, picture.PictureThumbnail.Length - 4);
            if(strTmp == picture.PictureId.ToString())
                filter = string.Format("*{0}_*.*", picture.PictureId.ToString());
            else
                filter = string.Format("*{0}_*.*", strTmp.ToString());
            List<String> urls = new List<string>();

            string orginalURL = strLocalThumbImagePath + picture.PictureThumbnail.ToString();
            string path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\thumbs";
            string[] currentFiles = System.IO.Directory.GetFiles(path, filter);

            foreach (string currentFileName in currentFiles)
            {
                string url = strLocalThumbImagePath + Path.GetFileName(currentFileName);

                if (url != orginalURL)
                    urls.Add(url);
            }

            //add original picture to array
            urls.Add(orginalURL);

            if (urls.Count > 0)
            {
                //reverse sort order (this way the biggest picture usally comes first..)
                urls.Reverse();
            }

            return urls;
        }

        public static void Delete(int pictureId)
        {
            Picture picture = GetPictureById(pictureId);
            string filter = String.Empty;
            string strTmp = picture.PictureThumbnail.Substring(0, picture.PictureThumbnail.Length - 4);
            if (strTmp == picture.PictureId.ToString())
                filter = string.Format("*{0}_*.*", picture.PictureId.ToString());
            else
                filter = string.Format("*{0}_*.*", strTmp.ToString());
            string path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\thumbs";
            string[] currentFiles = System.IO.Directory.GetFiles(path, filter);
            //delete the resized file
            foreach (string currentFileName in currentFiles)
            {
                string strPathFile = path + "\\" + Path.GetFileName(currentFileName);
                FileInfo file = new FileInfo(strPathFile);
                if (file.Exists)
                {
                    File.Delete(strPathFile);
                }                
            }
            //delete orginal file
            string orginalFile = path + "\\" + picture.PictureThumbnail;
            FileInfo orginalFileInfo = new FileInfo(orginalFile);
            if (orginalFileInfo.Exists)
            {
                File.Delete(orginalFile);
            } 
            //delete picture in database
            DBPicture.Delete(pictureId);
        }
    }
}
